﻿using Mapster;
using SageKing.Application.AspNetCore.SqlSugar.Extensions;
using System.Linq.Expressions;

namespace SageKing.Application.AspNetCore.SqlSugar.Service;

/// <summary>
/// SageKing消息结构实例表服务 
/// </summary>
/// <param name="repository"></param>
public class SysSageKingMessageInstanceService(SageKingRepository<SysSageKingMessageInstance> repository, SageKingRepository<SysSageKingMessageAttributeInstance> repositoryatt)
    : BaseService<SysSageKingMessageInstance>(repository)
{
    /// <summary>
    /// 获取one
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取one")]
    public virtual async Task<SysSageKingMessageInstance> GetOneWithChild(Expression<Func<SysSageKingMessageInstance, bool>> wherefunc)
    {
        var result = await repository.AsQueryable().Includes(a => a.Children).Where(wherefunc).FirstAsync();
        return result;
    }

    /// <summary>
    /// 获取数据 pos
    /// </summary>
    /// <param name="name"></param>
    /// <param name="version"></param>
    /// <returns></returns>
    public async Task<Dictionary<DataStreamTypeEnum, Dictionary<string, byte>>> GetPosDic(string name, long version)
    {
        var getFirst = await GetOneWithChild(a => a.Name == name && a.Version == version);
        if (getFirst == null || !getFirst.Children.HasItem())
        {
            return new Dictionary<DataStreamTypeEnum, Dictionary<string, byte>>();
        }
        return getFirst.GetPosDic();
    }

    /// <summary>
    /// 实例化检测,及写入实例化数据
    /// </summary>
    /// <param name="id"></param>
    /// <param name="version"></param>
    /// <returns></returns>
    public async Task<bool> InitData<T, Taa>(T entity)
        where T : SysSageKingMessageBase<Taa>
        where Taa : SysSageKingMessageAttributeBase
    {
        var check = await repository.IsAnyAsync(a => a.Name == entity.Name && a.Version == entity.Version);
        if (check)
        {
            return check;
        }
        if (entity.Children.Count <= 0)
        {
            return false;
        }

        //写入数据
        var entitySave = entity.Adapt<SysSageKingMessageInstance>();
        entitySave.Id = 0;
        var getMainId = await repository.InsertReturnSnowflakeIdAsync(entitySave);
        if (getMainId <= 0)
        {
            return false;
        }
        //明细表
        var entiyChildListSave = entity.Children.Adapt<SysSageKingMessageAttributeInstance[]>();
        foreach (var item in entiyChildListSave)
        {
            item.Id = 0;
            item.MessageId = getMainId;
        }
        var saveChild = await repositoryatt.InsertRangeAsync(entiyChildListSave);

        return saveChild;
    }
}
